/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MenuCadastrarEditarServicoPiscina.java
 *
 * Created on 21/09/2009, 10:26:41
 */

package JPaneis;

import Conector.Conector;
import Data.ServicoPiscina;
import java.awt.Component;
import java.awt.GridLayout;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import siii.MenuPadrao;


public class MenuCadastrarEditarServicoPiscina extends javax.swing.JPanel {

    private String objetivo;
    private MenuPadrao menuPadrao;
    private Conector conector;
    List<Map<String,?>> lista;
    private static final String numServ = "NUMERO_SERVICO";
    private ImageIcon iconeOK;
    private ImageIcon iconeERRO;
    private ImageIcon iconeATENCAO;

    /** Creates new form MenuCadastrarEditarServicoPiscina */
    public MenuCadastrarEditarServicoPiscina(MenuPadrao m, Conector con, String obj) {

        this.objetivo = obj;
        this.menuPadrao = m;
        this.conector = con;
        initComponents();
        if(this.objetivo.equals("C"))
            jButtonRemover.setVisible(false);
        else {
            servPiscServico.setEnabled(false);
            servPiscEspecie.setEnabled(false);
        }
        refreshList();
        getPeixesExpecies();
        iconeOK = new ImageIcon(getClass().getResource("/Images/fish-48x48ok.png"));
        iconeERRO = new ImageIcon(getClass().getResource("/Images/fish-48x48erro.png"));
        iconeATENCAO = new ImageIcon(getClass().getResource("/Images/fish-48x48atencao1.png"));
    }
          //create an instance of properties class
    public void getPeixesExpecies(){
           Properties props = new Properties();

          //try retrieve data from file
             try {

             props.load(new FileInputStream(java.net.URLDecoder.decode(getClass().getResource("/Conector/configuracoes.properties").getPath())));

             String message = props.getProperty("especies");

             servPiscEspecie.setModel(new javax.swing.DefaultComboBoxModel(message.split(",")));
             }

             //catch exception in case properties file does not exist

             catch(IOException e)
             {
             e.printStackTrace();
             }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabelPreco = new javax.swing.JLabel();
        jButtonRemover = new javax.swing.JButton();
        jLabelServPiscina = new javax.swing.JLabel();
        jButtonInserir = new javax.swing.JButton();
        jLabelEspecie = new javax.swing.JLabel();
        servPiscServico = new javax.swing.JComboBox();
        jLabelServico = new javax.swing.JLabel();
        jScrollPaneServPesc = new javax.swing.JScrollPane();
        jListServPisc = new javax.swing.JList();
        jButtonVoltar = new javax.swing.JButton();
        servPiscEspecie = new javax.swing.JComboBox();
        servPiscPreco = new javax.swing.JFormattedTextField();
        jLabel13 = new javax.swing.JLabel();
        jLabelPreco1 = new javax.swing.JLabel();

        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });

        jLabelPreco.setText("Preço Kg");

        jButtonRemover.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/peixe_cancelar2.png"))); // NOI18N
        jButtonRemover.setText("Remover");
        jButtonRemover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRemoverActionPerformed(evt);
            }
        });

        jLabelServPiscina.setFont(new java.awt.Font("Tahoma", 0, 24));
        jLabelServPiscina.setText("Serviço da Piscina");

        jButtonInserir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/peixe_add.png"))); // NOI18N
        jButtonInserir.setText("Inserir");
        jButtonInserir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonInserirActionPerformed(evt);
            }
        });

        jLabelEspecie.setText("Espécie");

        servPiscServico.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Limpo", "Sujo" }));
        servPiscServico.setName("Servico"); // NOI18N

        jLabelServico.setText("Serviço");

        jListServPisc.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jListServPisc.setName("Lista de Cadastro de Setviço de Pesca"); // NOI18N
        jListServPisc.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jListServPiscMouseClicked(evt);
            }
        });
        jScrollPaneServPesc.setViewportView(jListServPisc);

        jButtonVoltar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/salvar.png"))); // NOI18N
        jButtonVoltar.setText("Ok");
        jButtonVoltar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButtonVoltarMouseClicked(evt);
            }
        });
        jButtonVoltar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonVoltarActionPerformed(evt);
            }
        });

        servPiscPreco.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter()));

        jLabel13.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/servico_piscina.png"))); // NOI18N

        jLabelPreco1.setText("R$");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabelServPiscina, javax.swing.GroupLayout.PREFERRED_SIZE, 562, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(30, 30, 30)
                        .addComponent(jScrollPaneServPesc, javax.swing.GroupLayout.PREFERRED_SIZE, 324, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(68, 68, 68)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                    .addComponent(jLabelPreco)
                                    .addGap(18, 18, 18)
                                    .addComponent(jLabelPreco1)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(servPiscPreco))
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                    .addComponent(jLabelServico)
                                    .addGap(18, 18, 18)
                                    .addComponent(servPiscServico, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                    .addComponent(jLabelEspecie)
                                    .addGap(18, 18, 18)
                                    .addComponent(servPiscEspecie, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addComponent(jButtonInserir, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButtonRemover)
                                .addGap(18, 18, 18)
                                .addComponent(jButtonVoltar, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addGap(248, 248, 248))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(jLabelServPiscina, javax.swing.GroupLayout.DEFAULT_SIZE, 83, Short.MAX_VALUE)
                        .addGap(25, 25, 25))
                    .addComponent(jLabel13))
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(9, 9, 9)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabelServico)
                            .addComponent(servPiscServico))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabelEspecie)
                            .addComponent(servPiscEspecie))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabelPreco)
                            .addComponent(servPiscPreco)
                            .addComponent(jLabelPreco1))
                        .addGap(18, 18, 18)
                        .addComponent(jButtonInserir, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE)
                        .addGap(90, 90, 90)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButtonRemover)
                            .addComponent(jButtonVoltar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addComponent(jScrollPaneServPesc, javax.swing.GroupLayout.PREFERRED_SIZE, 276, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(95, 95, 95))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonInserirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonInserirActionPerformed
        try {
            if (this.objetivo.equals("C")) {
                ServicoPiscina servPiscina = this.readScreen();
                if (servPiscina != null) {
                    if (!conector.consultarServicoPiscinaCadastrado(servPiscina)) {
                        System.out.println("CADASTRANDO SERVICO");
                        if (conector.cadastrarServicoPiscina(servPiscina)) {
                            JOptionPane.showMessageDialog(this, "Serviço da Piscina cadastrado", "Confirmação", JOptionPane.WARNING_MESSAGE, iconeOK);
                        } else {
                            JOptionPane.showMessageDialog(this, "Serviço de Piscina não cadastrado", "Confirmação", JOptionPane.WARNING_MESSAGE, iconeERRO);
                        }
                    } else {
                        JOptionPane.showMessageDialog(this, "Serviço de Piscina previamente cadastrado", "Confirmação", JOptionPane.WARNING_MESSAGE, iconeERRO);
                    }
                } else {
                    JOptionPane.showMessageDialog(this, "Favor preencher Preço", "Confirmação", JOptionPane.WARNING_MESSAGE, iconeATENCAO);
                }
            } else if (this.objetivo.equals("E")) {
                if(jListServPisc.getSelectedIndex() != -1) {
                System.out.println("OBJETIVO: " + objetivo);
                ServicoPiscina servPiscina = this.readScreen();
                Map<String, ?> itens = lista.get(jListServPisc.getSelectedIndex());
                Integer numeroServico = (Integer) itens.get(numServ);
                System.out.println("ESTOU FAZENDO UPDATE DESTE SERVICO: " + servPiscina + " COM O NUMERO " + numeroServico);
                if (servPiscina != null) {
                    if (conector.atualizaServicoPiscina(servPiscina, numeroServico)) {
                        JOptionPane.showMessageDialog(this, "Serviço da Piscina atualizado", "Confirmação", JOptionPane.WARNING_MESSAGE, iconeOK);
                    } else {
                        JOptionPane.showMessageDialog(this, "Serviço de Piscina não cadastrado", "Confirmação", JOptionPane.WARNING_MESSAGE, iconeERRO);
                    }
                } else {
                    JOptionPane.showMessageDialog(this, "Favor preencher Valor", "Confirmação", JOptionPane.WARNING_MESSAGE, iconeATENCAO);
                }
            }
            else
                JOptionPane.showMessageDialog(this, "Favor selecionar o serviço a ser editado", "Atenção", JOptionPane.WARNING_MESSAGE, iconeATENCAO);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        // Atualiza a lista
        refreshList();
        cleanScreen();
    }//GEN-LAST:event_jButtonInserirActionPerformed

    private void jButtonRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRemoverActionPerformed
                //pega da lista numero do servico.
        if (lista.size() >= 0){
            Integer num = (Integer) lista.get(jListServPisc.getSelectedIndex()).get(numServ);
            // remove do bd
            conector.removerServicoPiscina(num);
        }
        // atualiza a lista
        refreshList();
    }//GEN-LAST:event_jButtonRemoverActionPerformed

    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        refreshList();
    }//GEN-LAST:event_formMouseClicked

    private void jButtonVoltarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButtonVoltarMouseClicked
        // TODO add your handling code here:
        cleanScreen();
        menuPadrao.trocaPanel2(menuPadrao.getMenuPrincipal());
        
    }//GEN-LAST:event_jButtonVoltarMouseClicked

    private void jButtonVoltarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonVoltarActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jButtonVoltarActionPerformed

    private void jListServPiscMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListServPiscMouseClicked
      if (lista.size() >= 0){
            //pega da lista numero do servico.
            Map<String, ?> itens = lista.get(jListServPisc.getSelectedIndex());
            // remove do bd

            setSelectedItem((String)itens.get("SERVICO"), servPiscServico);
            setSelectedItem((String)itens.get("ESPECIE"), servPiscEspecie);
            servPiscPreco.setValue(itens.get("VALOR"));
            jButtonInserir.setText("Atualizar");
        }
    }//GEN-LAST:event_jListServPiscMouseClicked

    public void setSelectedItem(String item, javax.swing.JComboBox combo) {

        if (combo.getItemCount() > 0) {
            for (int i = 0 ; i < combo.getItemCount(); i++){
                if(combo.getItemAt(i).equals(item.trim())){
                   // System.out.println("SELECIONOU " + i + ":" + item);
                    combo.setSelectedIndex(i);
                    break;
                }

            }
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonInserir;
    private javax.swing.JButton jButtonRemover;
    private javax.swing.JButton jButtonVoltar;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabelEspecie;
    private javax.swing.JLabel jLabelPreco;
    private javax.swing.JLabel jLabelPreco1;
    private javax.swing.JLabel jLabelServPiscina;
    private javax.swing.JLabel jLabelServico;
    private javax.swing.JList jListServPisc;
    private javax.swing.JScrollPane jScrollPaneServPesc;
    private javax.swing.JComboBox servPiscEspecie;
    private javax.swing.JFormattedTextField servPiscPreco;
    private javax.swing.JComboBox servPiscServico;
    // End of variables declaration//GEN-END:variables

    void refreshList() {

        try {
            lista = (List<Map<String,?>>) conector.doRawSql("SELECT * FROM SERVICOS_DISPONIVEIS_PISCINA");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
         // String[][] dados = getListData();
          String[][] dados = getListData();
          //set list for JList
          if (dados != null){
            jListServPisc.setListData(dados);
            //create Renderer and dislpay
            System.out.println("colunas: " + dados[0].length);
            jListServPisc.setCellRenderer(new MyCellRenderer(dados[0].length));
          } else {
              jListServPisc.setListData(new String[]{});
          }
    }
        private String[][] getListData(){
        String[][] dados = null;
      //  String campos = "NUMERO_SERVICO, ESPECIE, SERVICO, VALOR";
      //  List<Map<String,?>> lista = null;
        
        System.out.flush();
        int line = 0;
        int col = 0 ;

        for(Map<String,?> m : lista){
            if (dados == null){
                dados = new String[lista.size()][m.size()];
            }
            System.out.println(m);
            for(String key : m.keySet()){
                if (key.equals(numServ))
                    continue;
                System.out.println(key + ":" + m.get(key) + ":" + line + ":" + col);
                dados[line][col++] = m.get(key).toString();
            }
            line++;
            col=0;
        }

        return dados;
    }

    private void cleanScreen() {
        servPiscServico.setSelectedItem("Limpo");
        servPiscEspecie.setSelectedItem("Abotoado");
        servPiscPreco.setText("");

    }

    static class MyCellRenderer extends JPanel implements ListCellRenderer {

        ArrayList<JLabel> labels = new ArrayList();
        JLabel left, middle, right;
        int cols;

        MyCellRenderer(int cols) {
            this.cols = cols;
            setLayout(new GridLayout(1, cols));
            for (int i=0; i < cols;i++){
                JLabel label = new JLabel();
                label.setOpaque(true);
                add(label);
                labels.add(label);
            }
        }

        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            int i = 0;
            for (JLabel jl : labels) {
                jl.setText(((String[])value)[i++]) ;
                if (isSelected) {
                    jl.setBackground(list.getSelectionBackground());
                    jl.setForeground(list.getSelectionForeground());
                } else {
                    jl.setBackground(list.getBackground());
                    jl.setForeground(list.getForeground());
                }
            }

            setEnabled(list.isEnabled());
            setFont(list.getFont());
            return this;
        }
    }

    private ServicoPiscina readScreen() throws ParseException {

    String servico, especie;
    float valor;
         servico = servPiscServico.getSelectedItem().toString();
         especie = servPiscEspecie.getSelectedItem().toString();
         if(!servPiscPreco.getText().replace(",", ".").equals(""))
            valor = Float.parseFloat(servPiscPreco.getText().replace("R","").replace("$", "").replace(",", "."));
         else
             return null;


         ServicoPiscina serv_piscina = new ServicoPiscina(servico, especie, valor);
         return serv_piscina;
    }
}
